from django.contrib.auth.backends import ModelBackend

from accounts.models import *

class AccountBackend(ModelBackend):
	"Authenticates based on AccountUser.username and Account."
	
	def authenticate(self, username=None, password=None):
		"""
		Given a `username` and `password`, find and return an
		AccountUser for the current Account.  `username` is
		AccountUser.username, while `password` is AccountUser.user.password.
		"""
		try:
			account = Account.objects.get(site__id=settings.SITE_ID)
			try:
				account_user = AccountUser.objects.get(account=account, username=username)
				if account_user.user.check_password(password):
					return account_user.user
				else:
					return None
			except AccountUser.DoesNotExist:
				return None
		except Account.DoesNotExist:
			return None